package com.clz.util;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JDBCUtils {
    private static DataSource dataSource = null;

    static {
        try {
            String url = "jdbc:mysql://localhost:3306/clz_10?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
            String username = "root";
            String password = "123456";
            dataSource = new DriverManagerDataSource(url, username, password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static JdbcTemplate getJdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 开启事务
     *
     * @return 返回一个Connection对象
     */
    public static Connection startTransaction() {
        //在获取连接之前开启线程与连接的绑定
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {//判断线程绑定是否开启
            //如果没开启，则进行线程绑定
            TransactionSynchronizationManager.initSynchronization();

        }
        Connection conn = DataSourceUtils.getConnection(getDataSource());
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    public static void commit(Connection conn) {
        if (conn != null) {
            try {
                conn.commit();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                clear(conn);
            }
        }
    }

    public static void rollback(Connection conn) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                clear(conn);
            }
        }
    }

    public static void clear(Connection conn) {
        //清除同步状态，即当前线程绑定的的connection连接
        TransactionSynchronizationManager.clear();
        //解除绑定的的connection连接
        TransactionSynchronizationManager.unbindResourceIfPossible(getDataSource());
        //归还数据库连接至连接池
        if (conn != null) {//非空判断，确认不为空再归还
            DataSourceUtils.releaseConnection(conn, getDataSource());
        }
    }


}
